package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AfterSaleOutHouse;
import com.sl.au.entity.AfterSaleTicket;
import com.sl.au.entity.AfterSaleTicketAdvice;
import com.sl.au.entity.AfterSaleTicketBack;
import com.sl.au.entity.AfterSaleTicketTrance;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.Chance;
import com.sl.au.entity.Customer;
import com.sl.au.entity.JPushMsg;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.service.AfterSaleOutHouseService;
import com.sl.au.service.AfterSaleTicketService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.JGPushService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;

/*
 * 售后外勤
 */

@RestController
@RequestMapping(value = "/ui/afterSaleOutHouse")
public class AfterSaleOutHouseController extends BaseController {

	@Autowired
	AfterSaleOutHouseService afterSaleOutHouseService;

	@Autowired
	OptionService optionService;
	
	@Autowired
	AttachmentService attachmentService;

	@Autowired
	AfterSaleTicketService afterSaleTicketService;

	@Autowired
	OperateLogService operateLogService;

	@Autowired
	UserService userService;
	
	@Autowired
	JGPushService jPushService;
	

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("afterSaleOutHouse/outHouseindex");
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getOutHousePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		if (key == null) {
			key = "";
		}
		condition.put("key", key);

		condition.put("userId", userId);
		List<AfterSaleOutHouse> afterSaleOutHouses = afterSaleOutHouseService.getOutHouseTicket(start, length,
				condition, null, null);
		long count = afterSaleOutHouseService.getRepository().getCountBykey(condition.get("userId"),
				condition.get("key"));
		map.put("data", afterSaleOutHouses);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	@RequestMapping(value = "getOutHouseTicketCount", method = RequestMethod.GET)
	public Map<String, Object> getOutHouseTicketCount(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		key="";
		condition.put("key", key);
		condition.put("userId", userId);
		long count = afterSaleOutHouseService.getRepository().getCountBykey(condition.get("userId"),
				condition.get("key"));
		map.put("data", count);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "getMyTicketPage", method = RequestMethod.GET)
	public Map<String, Object> getMyOutHousePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String outState = request.getParameter("outState");
		if (outState == null) {
			outState = "";
		}
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("outState", outState);
		List<AfterSaleOutHouse> afterSaleOutHouses = afterSaleOutHouseService.getMyOutHouseTicket(start, length,
				condition, null, null);
		List<AfterSaleOutHouse> afters=new ArrayList<AfterSaleOutHouse>();
		long count = afterSaleOutHouseService.getRepository().getMyCountBykey(condition.get("userId"),
				condition.get("key"),condition.get("outState"));
		
		for(AfterSaleOutHouse o:afterSaleOutHouses){
			String parentId = o.getAfterSaleTicket().getId();
			List<Attachment> t = attachmentService.getRepository().findByParentId(parentId);
			int num = t.size();
			o.setAttachNumber(num);
			afters.add(o);
		}

		map.put("data", afters);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	@RequestMapping(value = "getMyTicketPageCount", method = RequestMethod.GET)
	public Map<String, Object> getMyOutHouseCount(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		String key = request.getParameter("key");
		String outState = request.getParameter("outState");
		if (outState == null) {
			outState = "";
		}
        key="";
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("outState", outState);
		long count = afterSaleOutHouseService.getRepository().getMyCountBykey(condition.get("userId"),
				condition.get("key"),condition.get("outState"));
		map.put("data", count);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 服务单派遣保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> TicketSend(HttpServletRequest request,
			@RequestBody AfterSaleOutHouse afterSaleOutHouse) {
		Map<String, Object> map = new HashMap<String, Object>();
		afterSaleOutHouseService.getRepository().save(afterSaleOutHouse);
		Account a = this.getMyAccount();
		User user = a.getUser();
		AfterSaleTicket ticket = afterSaleTicketService.getTicketRepository()
				.findOne(afterSaleOutHouse.getAfterSaleTicket().getId());
		User staff = userService.getRepository().findOne(afterSaleOutHouse.getUser().getId());
		
		List<String> list = new ArrayList<>();
		list.add(ExdeUtil.splitString(staff.getId()));
		System.out.println("外勤"+staff.getName());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("售后信息待处理：" + user.getName() + "将合同号为：" + ticket.getContractCode() + "的售后信息派遣给你。");
		msg.setTitle("售后信息" + ticket.getAfterSaleType());
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "派遣服务单【" + ticket.getUnitName() + "】给【" + staff.getEmpLogin().getUserName() + "】";
		operateLogService.log(user, "售后服务办理", content);
		String outId=afterSaleOutHouse.getId();
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		map.put("outId", outId);
		return map;
	}

	/**
	 * 跟踪服务单页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/trance", method = RequestMethod.GET)
	public ModelAndView saleChanceDetail(HttpServletRequest request) {
		String type = request.getParameter("type");
		String ticketId = request.getParameter("ticketId");
		String outServiceId = request.getParameter("outServiceId");
		String sendReason="";
		AfterSaleOutHouse out=afterSaleOutHouseService.getRepository().findOne(outServiceId);
		if(out!=null){
			sendReason=out.getSendReason();
		}
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		ModelAndView modelAndView = null;
		if (type.equals("三包办理")) {
			modelAndView = this.createLayoutView("afterSaleOutHouse/outHouseTranceThree");
		} else {
			modelAndView = this.createLayoutView("afterSaleOutHouse/outHouseTrancePayment");
		}
		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);
		// tab2页数据
		List<AfterSaleTicketBack> afterSaleTicketBacks = afterSaleOutHouseService.getRepository()
				.getTicketTab2Data(ticketId);
		// tab3页数据
		List<AfterSaleTicketAdvice> afterSaleTicketAdvices = afterSaleOutHouseService.getRepository()
				.getTicketTab3Data(ticketId);
		AfterSaleTicketBack afterSaleTicketBack = afterSaleTicketBacks.get(0);
		AfterSaleTicketAdvice afterSaleTicketAdvice = afterSaleTicketAdvices.get(0);
		String isGuarantee = afterSaleTicketBack.getIsGuarantee();
		modelAndView.addObject("afterSaleTicket", afterSaleTicket);
		modelAndView.addObject("qualityGuarantee", isGuarantee);
		modelAndView.addObject("afterSaleTicketBack", afterSaleTicketBack);
		modelAndView.addObject("afterSaleTicketAdvice", afterSaleTicketAdvice);
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("outServiceId", outServiceId);
		modelAndView.addObject("sendReason", sendReason);
		return modelAndView;
	}

	/**
	 * 服务单跟踪保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/tranceSave", method = RequestMethod.POST)
	public Map<String, Object> tranceSave(HttpServletRequest request,
			@RequestBody AfterSaleTicketTrance afterSaleTicketTrance) {
		Map<String, Object> map = new HashMap<String, Object>();
		afterSaleOutHouseService.getTicketTranceRepository().save(afterSaleTicketTrance);
		Account a = this.getMyAccount();
		User user = a.getUser();
		AfterSaleTicket ticket = afterSaleTicketService.getTicketRepository()
				.findOne(afterSaleTicketTrance.getAfterSaleTicket().getId());
		String content = "跟踪服务单【" + ticket.getUnitName() + "】";
		operateLogService.log(user, "售后服务执行", content);
		map.put("code", 0);
		return map;
	}

	/**
	 * 获取一次派遣单的活动记录数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getTrancePage", method = RequestMethod.GET)
	public Map<String, Object> getTrancePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String outId=request.getParameter("outId");
		condition.put("outId", outId);
		/*
		 * String ticketId = request.getParameter("ticketId"); String user_Id =
		 * request.getParameter("userId"); Account a = this.getMyAccount();
		 * String userId = a.getUser().getId(); if (user_Id != null) { userId =
		 * user_Id; } condition.put("ticketId", ticketId);
		 * condition.put("userId", userId); List<AfterSaleTicketTrance>
		 * afterSaleTicketTrances =
		 * afterSaleOutHouseService.getTicketTrance(start, length, condition,
		 * null, null); long count =
		 * afterSaleOutHouseService.getRepository().getTickettranceCount(
		 * condition.get("userId"), condition.get("ticketId"));
		 */
		List<AfterSaleTicketTrance> afterSaleTicketTrances = afterSaleOutHouseService.findAllTrance(start, length,
				condition, null, null);
		long count=afterSaleOutHouseService.getRepository().getTranceCount(outId);
		map.put("data", afterSaleTicketTrances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 获取跟踪情况数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getTrancePersonPage", method = RequestMethod.GET)
	public Map<String, Object> getTrancePersonPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String ticketId = request.getParameter("ticketId");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		condition.put("ticketId", ticketId);
		condition.put("userId", userId);
		List<AfterSaleOutHouse> afterSaleOutHouses = afterSaleOutHouseService.getTicketTrancePerson(start, length,
				condition, null, null);
		long count = afterSaleOutHouseService.getRepository().getTickettranceCount(condition.get("ticketId"));

		map.put("data", afterSaleOutHouses);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public Map<String, Object> delBid(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<AfterSaleTicketTrance> sfterSaleTicketTrances = new ArrayList<AfterSaleTicketTrance>();
		for (int i = 0; i < id.length; i++) {
			String outId = id[i];
			AfterSaleTicketTrance afterSaleTicketTrance = new AfterSaleTicketTrance();
			afterSaleTicketTrance.setId(outId);
			sfterSaleTicketTrances.add(afterSaleTicketTrance);
		}
		afterSaleOutHouseService.getTicketTranceRepository().deleteInBatch(sfterSaleTicketTrances);
		map.put("code", 0);
		return map;
	}

	/*
	 * 获得服务单的完成情况
	 */
	@RequestMapping(value = "/getTicketState", method = RequestMethod.GET)
	public Map<String, Object> getTicketState(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ticketId = request.getParameter("ticketId");
		int state = afterSaleOutHouseService.getTicketFinishState(ticketId);
		map.put("code", state);
		return map;
	}
	//移动端接收服务单
	@RequestMapping(value = "receiveTicket", method = RequestMethod.GET)
	public Map<String, Object> receiveTicket(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ticketId = request.getParameter("ticketId");
		String id = request.getParameter("id");
		AfterSaleOutHouse ticket=afterSaleOutHouseService.getRepository().findOne(id);
		ticket.setIsReceived(1);
		ticket.setOutState("1");
		AfterSaleTicket ticketQuery=afterSaleTicketService.getTicketRepository().findOne(ticketId);
		ticketQuery.setIsSubmit("4");
		afterSaleOutHouseService.getRepository().save(ticket);
		afterSaleTicketService.getTicketRepository().save(ticketQuery);
		map.put("data", ticket);
		return map;
	}
	//移动端跟踪情况录入
	@RequestMapping(value = "/mobileTranceSave", method = RequestMethod.POST)
	public Map<String, Object> mobileTranceSave(HttpServletRequest request,
			@RequestBody AfterSaleTicketTrance afterSaleTicketTrance) {
		Map<String, Object> map = new HashMap<String, Object>();
		afterSaleOutHouseService.getTicketTranceRepository().save(afterSaleTicketTrance);
		AfterSaleOutHouse ticket=afterSaleOutHouseService.getRepository().
				findOne(afterSaleTicketTrance.getAfterSaleOutHouse().getId());
		ticket.setOutState("2");
		afterSaleOutHouseService.getRepository().save(ticket);
		Account a = this.getMyAccount();
		User user = a.getUser();
		AfterSaleTicket ticketQuery = afterSaleTicketService.getTicketRepository()
				.findOne(afterSaleTicketTrance.getAfterSaleTicket().getId());
		String content = "跟踪服务单【" + ticketQuery.getUnitName() + "】";
		operateLogService.log(user, "售后服务执行", content);
		map.put("code", 0);
		return map;
	}
	//移动端完成派遣单
	@RequestMapping(value = "finishTicket", method = RequestMethod.GET)
	public Map<String, Object> finishTicket(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String afterSummary = request.getParameter("afterSummary");
		AfterSaleOutHouse ticket=afterSaleOutHouseService.getRepository().findOne(id);
		ticket.setIsFinish(1);
		ticket.setOutState("3");
		ticket.setAfterSummary(afterSummary);
		String ticketId=ticket.getAfterSaleTicket().getId();
		AfterSaleTicket ticketQuery=afterSaleTicketService.getTicketRepository().findOne(ticketId);
		if(afterSaleOutHouseService.getTicketFinishState(ticketId)==0){
			ticketQuery.setIsSubmit("5");
		}
		afterSaleOutHouseService.getRepository().save(ticket);
		afterSaleTicketService.getTicketRepository().save(ticketQuery);
		map.put("code", 0);
		return map;
	}
}
